package com.cc.jcmplayer;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.util.Log;

import android.opengl.GLSurfaceView;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.view.View;

import android.net.Uri;

import android.app.Activity;

import android.Manifest;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.content.pm.PackageManager;
import android.widget.Toast;

import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private  final int FILE_VIDEO_REQUEST_CODE = 100;
    private  final int REQUEST_EXTSTORAGE_CODE = 1024;
    private  String[] STORAGE_PERMISSIONS = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE };

    private GLSurfaceView m_glSurfaceView;
    private JCMPlayer     m_jcmplayer;
    private SeekBar       m_seekBar;

    private float         m_videoRatio;
    private float         m_videoTotalSeconds;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        verifyStoragePermissions(this);


        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        m_videoRatio = 0;
        m_videoTotalSeconds =0;

        m_seekBar = (SeekBar)findViewById(R.id.seekBar);
        m_seekBar.bringToFront();
        m_seekBar.setProgress(0);
        m_seekBar.setOnSeekBarChangeListener(onSeekBarChangeListener);

        m_jcmplayer = new JCMPlayer(this);

        m_glSurfaceView = (GLSurfaceView)findViewById(R.id.surfaceView);
        m_glSurfaceView.setEGLContextClientVersion(3);
        m_glSurfaceView.setRenderer(m_jcmplayer);
        m_glSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY); // GLSurfaceView.RENDERMODE_WHEN_DIRTY

        View customToolbar = findViewById(R.id.custom_toolbar);
        TextView barText=(TextView)customToolbar.findViewById(R.id.toolbar_textView);
        ImageButton barBtn= (ImageButton)customToolbar.findViewById(R.id.toolbar_button);

        barBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("video/*");
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                try {
                    startActivityForResult( Intent.createChooser(intent, "Select a File to Upload"), FILE_VIDEO_REQUEST_CODE);
                } catch (android.content.ActivityNotFoundException ex) {
                    Log.d("FileDialog","Open File Dialog Error...");
                }
            }
        });

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);   //应用运行时，保持屏幕高亮，不锁屏
    }

//    private boolean checkPersmissionsGranted(String[] permissions){
//        for(String permis : permissions){
//            if(ContextCompat.checkSelfPermission(this,permis) != PackageManager.PERMISSION_GRANTED){
//                return false;
//            }
//        }
//        return true;
//    }

    @Override
    protected void onStart()
    {
        super.onStart();
        m_jcmplayer.InitVideoPlayer();
    }


    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        m_jcmplayer.StopVideoPlayer();
    }


    public void UpdateVideoRenderCallback()
    {
        m_glSurfaceView.requestRender();

    }

    private void updateVideoSize()
    {

        WindowManager manager = this.getWindowManager();
        DisplayMetrics outMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(outMetrics);
        int width = outMetrics.widthPixels;
        int height = outMetrics.heightPixels;


        int topMargin = 0;
        if(m_videoRatio > 1){
            topMargin = 200;
        }else{
            topMargin = 200;
        }

        ConstraintLayout.LayoutParams layoutParams=(ConstraintLayout.LayoutParams)m_glSurfaceView.getLayoutParams();
        layoutParams.topMargin = topMargin;
        layoutParams.leftMargin = 0;
        layoutParams.rightMargin = 0;
        layoutParams.width = width;
        layoutParams.height = (int)(width / m_videoRatio);

        m_glSurfaceView.setLayoutParams(layoutParams);
    }

    private SeekBar.OnSeekBarChangeListener onSeekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
           if (fromUser) { // 确保只有用户操作时才进行处理
               float currSliderRatio = progress /1000.0f; // 当前进度
               float seekingTime = currSliderRatio * m_videoTotalSeconds; // 当前进度对应的时间
               if (seekingTime > m_videoTotalSeconds) {
                   seekingTime = m_videoTotalSeconds;
               }
               Log.d("MainActivity", "Seeking Time: " + seekingTime);
               m_jcmplayer.SeekVideoPlayer(seekingTime);

           }

//            if(progress % 10 == 0){
//               Log.d("","当前进度：" + progress);
//
//               onSeekingVideo(progress);
//           }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            // 可以在这里暂停视频播放，避免拖动时画面闪烁
            m_jcmplayer.PauseVideoPlayer();
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            Log.d("MainActivity", "结束：" + seekBar.getProgress());
            int currValue = seekBar.getProgress();
            onSeekingVideo(currValue);
            // 拖动结束后恢复视频播放
            //m_jcmplayer.ResumeVideoPlayer();
        }
    };

    private void onSeekingVideo(float aValue){

        float currSliderRatio = aValue /1000.0f;
        float seekingTime = currSliderRatio * m_videoTotalSeconds;

        if(seekingTime > m_videoTotalSeconds){
            seekingTime = m_videoTotalSeconds;
        }
        Log.d("MainActivity","Seeking Time: "+ seekingTime);
        m_jcmplayer.SeekVideoPlayer(seekingTime);
    }

    private  void verifyStoragePermissions(Activity activity) {

        List<String> permissionsList = new ArrayList<>();
        permissionsList.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        permissionsList.add(Manifest.permission.MANAGE_EXTERNAL_STORAGE);

        PermissionsUtil.requestPermissions(this,permissionsList);

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        Boolean bStorage = false;

        if (requestCode == PermissionsUtil.REQUEST_ALL_PERMISSION_REQ_CODE) {
            for(String perms : permissions){
                if(perms.equals("android.permission.READ_EXTERNAL_STORAGE")){
                    bStorage = true;
                    Log.d("","EXTStorage permission Success.");
                    break;
                }
                Log.d("","Permissionss------->>>"+perms);
            }
        }

        if(!bStorage){
            //ToastUtils.show("存储权限获取失败");
             Log.d("","EXTStorage permission faild");
            Toast.makeText(this,"EXTStorage request failed.",Toast.LENGTH_LONG).show();;
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

         if(requestCode == FILE_VIDEO_REQUEST_CODE)
        {
            if (resultCode == RESULT_OK) {
                Uri uri = data.getData();
                String path = FileUtils.getPath(this,uri);
                Log.d("MainActivity","File Path: "+path+" URI: "+uri);
                m_jcmplayer.StartVideoPlayerWithPath(path);
                m_videoRatio = m_jcmplayer.GetVideoSizeRatio();
                m_videoTotalSeconds = m_jcmplayer.GetVideoTotalSeconds();
                Log.d("MainActivity","video ratio: "+m_videoRatio);
                Log.d("MainActivity","video total seconds: "+ m_videoTotalSeconds);
                m_seekBar.setProgress(0);
            }
            updateVideoSize();
        }

    }


    private void writeFile() {
        Toast.makeText(this,"success",Toast.LENGTH_LONG).show();;

    }

}